package com.example.demo.limit.java;

import com.example.demo.limit.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author lyc
 * @date 2019/6/11.
 */
@Slf4j
@Service
public class SemaphoreLimitServiceImpl implements LimitService {

    // 线程池
    ExecutorService exec = Executors.newCachedThreadPool();
    // 只能5个线程同时访问
    final Semaphore semp = new Semaphore(5);

    @Override
    public void limit() {
        // 模拟20个客户端访问
        for (int index = 0; index < 20; index++) {
            final int NO = index;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        // 获取许可 一直阻塞
                        semp.acquire();
                       // semp.tryAcquire(1, TimeUnit.MINUTES); //这个尝试 多长时间获取 到
                        //处理业务
                        log.info("Accessing: " + NO);
                        Thread.sleep((long) (Math.random() * 10000));
                        log.info("存在多少有效" + semp.availablePermits());
                    } catch (InterruptedException e) {
                        log.info("error:{}",e);
                    } finally {
                        // 访问完后，释放
                        semp.release();
                    }
                }
            };
            exec.execute(run);
        }
        // 退出线程池
        //exec.shutdown();
    }
}